<?php
namespace catchAdmin\storehouse\model;

use catchAdmin\basics\model\Provider;
use catchAdmin\stock\model\Pick;
use catchAdmin\storehouse\model\search\WarehouseOutSearch;
use catcher\base\CatchModel;
use catcher\CatchAuth;
use think\facade\Db;

class WarehouseOut extends CatchModel
{

    use WarehouseOutSearch;

    protected $name = 'db_warehouse_out';
    protected $field = [
        'id', //
        'warehouse_out_id', // 出库主单编号
        'project_id', // 项目id(关联项目表)
        'project_client', // 委托方ID(关联项目的下级分类表)
        'customer_business_number', // 客户业务单号
        'customer_order_type', // 出库客户订单类型
        'entry_method', // 录入方式
        'transport_type', // 运输方式
        'driver_name', // 司机名称
        'driver_phone', // 司机电话
        'driver_plate', // 车牌号
        'set_out_address', // 出发地
        'shipper', // 发货方
        'shipper_name', // 发货联系人姓名
        'shipper_phone', // 发货人联系电话
        'shipper_city', // 发货方省/市/区
        'shipper_address', // 发货人具体地址
        'ship_to', // 收货方
        'ship_to_name', // 收货联系人姓名
        'ship_to_phone', // 收货人联系电话
        'ship_to_city', // 收货方省/市/区
        'ship_to_address', // 收货人具体地址
        'odd_numbers_one', // 参考单号1
        'odd_numbers_two', // 参考单号2
        'odd_numbers_three', // 参考单号3
        'remarks', // 备注
        'status', // 出库状态
        'tenant_id', // 商户id
        'creator_id', // 创建者ID
        'created_at', // 创建时间
        'updated_at', // 更新时间
        'deleted_at', // 删除状态，0未删除 >0 已删除
        'new_settlement',//结算方
        'new_customer_name',//客户名称
        'new_trade_clause',//贸易条款
        'new_order_date',//订单创建日期
        'new_goods_description',//货品品名描述
        'Original',//Original
        'Destination',//Destination
        'new_exporting_country',//出口国
        'new_destination_country',//目的国
        'new_order_status',//订单状态
        'new_tray_num',//货物托盘数量
        'new_box_num',//货物箱数,
        'new_gross_weight',
        'actual_number',//实际出库数量
        'goods_number',//要求出库数量
        'shipper_serial_number',//托运人 代码 C0001
        'shipper_relation_name',//联系人
        'shipper_relation_phone',//联系方式
        'shipper_addr',//联系地址
        'consignee_serial_number',//收货人 代码 C0002
        'consignee_relation_name',//联系人
        'consignee_relation_phone',//联系方式
        'consignee_addr',//地址
        'delivery_config_id',//收货地-库名ID
        'delivery_addr',//库名地址
        'delivery_config_name',//库名
        'waybill',//运单号
        'clause',//条款
        'deliver_serial_number',
        'deliver__relation_name',
        'deliver_relation_phone',
        'deliver_addr',
        'PO',
        'DO',
        'CO',
        'SN',
        'LOT1',
        'LOT2',
        'LOT3',
        'new_goods_dimension',
        'new_goods_price',
        'edi_json',
        'edi_return',
        'packing_box',//包装箱
        'support_export',//支持导出
    ];
    /**
     *
     *
     * @time 2019年12月08日
     * @return array|\think\Paginator
     *@throws \think\db\exception\DbException
     */
    public function getList($tenant_id=0,$project_name='',$id = 0,$position=0,$type=0)
    {
        $user = (new CatchAuth())->user();
        $user_id = $user->id;
        $where = [];
        if($tenant_id !== 0){
            $where[]=['w.tenant_id','=',$tenant_id];
//            if($type==3 && $position!=1) {
//                $where[] = ['w.creator_id', '=', $id];
//            }

            if($type==3){//员工账号，拿到所有项目
                $projectIds = (new Project)->where([
                    ['pid','>',0],
                    ['tenant_id','=',$tenant_id],
                    ['employees','find in set', $user_id],
                ])->column('project_id');
                $where[] = ['w.project_client','in',$projectIds];
            }
        }
//        if($project_name){
//            $where[]=['p.project_name','like',"%$project_name%"];
//        }
        $sn = request()->param('sn');
        return $this->field('w.*')//withoutField(['updated_at'], true)
        ->catchSearch()
            ->alias('w')
            ->leftJoin('db_project p','w.project_id = p.project_id')
            ->where($where)
            ->where(function($query)use($sn){
                if(!empty($sn)){
                    $outId = DB::table('db_pick')->where('sn',$sn)
                        ->value('warehouse_out_id');
                    $query->where('w.warehouse_out_id',$outId);
                }
            })
            ->order($this->aliasField('id'), 'desc')
            ->paginate()
            ->each(function (&$item){
                $item['pick_num'] =Pick::where('warehouse_out_id',$item['warehouse_out_id'])->count('sn');

                $item['client_name'] = Db::table('db_project')
                    ->where(['project_id' => $item['project_client']])
                    ->value('project_name');
                $item['project_name'] = Db::table('db_project')
                    ->where(['project_id' => $item['project_id']])
                    ->value('project_name');
                $item['project_id'] = [$item['project_id'],$item['project_client']];
                $item['ship_to_city'] = json_decode($item['ship_to_city'],true);
                $item['shipper_city'] = json_decode($item['shipper_city'],true);
                $item['pub_name'] = Db::table('users')
                    ->where([['deleted_at','=',0],['id','=',$item['creator_id']]])
                    ->value('username');

                if($item['packing_box']){
                    $item['packing_box'] = explode(',',$item['packing_box']);
                }else{
                    $item['packing_box'] = [];
                }
            });
    }


//    public static function onBeforeInsert($warehouse_out)
//    {
//        $warehousing_count = Db::table('db_warehousing')->where('tenant_id',$warehouse_out->tenant_id)->whereMonth('created_at')->count();
//        $warehouse_out_count = Db::table('db_warehouse_out')->where('tenant_id',$warehouse_out->tenant_id)->whereMonth('created_at')->count();
//        $new_id = $warehousing_count + $warehouse_out_count;
//
//        $co_code = Db::table('users')->where('id',$warehouse_out->tenant_id)->value('co_code');
//        if($co_code){
//            $head = strtoupper($co_code) . "OB";
//        }else{
//            $head = "CIWUXCN" . "OB";
//        }
//
//        $yearMonth = date("ym");
//        if (!empty($warehouse_out->remarks) && preg_match('/^\d{10}$/', $warehouse_out->remarks)) {
//            $yearMonth = date("ym",$warehouse_out->remarks);
//        }
//
//        $warehouse_out->warehouse_out_id = $head . $yearMonth . str_pad($new_id + 1,5,'0',STR_PAD_LEFT);
//    }


    public static function onAfterInsert($warehouse_out)
    {
        $warehousing_count = Db::table('db_warehousing')->where('tenant_id',$warehouse_out->tenant_id)->whereMonth('created_at')->count();
        $warehouse_out_count = Db::table('db_warehouse_out')->where('tenant_id',$warehouse_out->tenant_id)->whereMonth('created_at')->count();
        $new_id = $warehousing_count + $warehouse_out_count;

        $co_code = Db::table('users')->where('id',$warehouse_out->tenant_id)->value('co_code');
        if($co_code){
            $head = strtoupper($co_code) . "OB";
        }else{
            $head = "CIWUXCN" . "OB";
        }

        $yearMonth = date("ym");
        if (!empty($warehouse_out->remarks) && preg_match('/^\d{10}$/', $warehouse_out->remarks)) {
            $yearMonth = date("ym",$warehouse_out->remarks);
        }

        if($warehouse_out->tenant_id == '10148'){
            $warehouse_out->warehouse_out_id = $head . $yearMonth . str_pad($new_id,5,'0',STR_PAD_LEFT);
        }else{
            $warehouse_out->warehouse_out_id = $head . $yearMonth . str_pad($new_id + 1,5,'0',STR_PAD_LEFT);
        }

        $warehouse_out->save();
    }

    public function todayNumber(){
        $user = (new CatchAuth)->user();

        $where = [
            ['deleted_at','=',0],
        ];

        if($user['type'] !== 1) {//普通商户
            $where[] = ['tenant_id','=',$user['tenant_id']];
        }

        $warehouseOut = $this->where($where)->whereDay('created_at')->field('IFNULL(SUM(goods_number),0) as total_number,IFNULL(SUM(actual_number),0) as already_number')->find();

        return $warehouseOut;
    }

    //导出需要的基础数据
    public function getExportData($warehouse_out_id){
        $warehouseOut = (new WarehouseOut)->alias('wo')
//            ->field("wo.*,pr.account_code,u.username as pub_name,dp1.account_key as _shipper_serial_number,dp2.account_key as _consignee_serial_number")
            ->field("wo.*,pr.account_code,u.username as pub_name")
            ->leftJoin('db_project p','p.project_id = wo.project_client')
            ->leftJoin('db_provider pr','pr.id = p.provider_id')
            ->leftJoin('users u','u.id = wo.creator_id')
//            ->leftJoin('db_provider dp1','dp1.serial_number = wo.shipper_serial_number')
//            ->leftJoin('db_provider dp2','dp2.serial_number = wo.consignee_serial_number')
            ->where('warehouse_out_id',$warehouse_out_id)
            ->find()->toArray();

        if($warehouseOut['shipper_serial_number']){
            $warehouseOut['shipper_serial_number'] = (new Provider())
                ->where('serial_number',$warehouseOut['shipper_serial_number'])->value('account_code');
        }
        if($warehouseOut['consignee_serial_number']){
            $warehouseOut['consignee_serial_number'] = (new Provider())
                ->where('serial_number',$warehouseOut['consignee_serial_number'])->value('account_code');
        }

        $warehouseOutSon =(new WarehouseOutSon )
            ->alias('wos')
            ->field('wos.*,p.serial_number,pa.layup_num as _layup_num')
            ->leftJoin('db_product p','p.goods_id = wos.goods_id')
            ->leftJoin('db_packing pa','wos.packing_id = pa.packing_id')
            ->where('warehouse_out_id',$warehouse_out_id)
            ->order('wos.id','asc')
            ->select()->toArray();


        $pick =  (new Pick)->alias('p')
            ->field('p.*,wc.name,pro.new_item_number,pro.goods_name,pro.goods_Cname,s.stock_id as _stock_id,w.customer_business_number as ing_customer_business_number,
                s.Good_Qty as _Good_Qty,s.Hold_Qty as _Hold_Qty,s.NG_Qty as _NG_Qty
            ')
            ->leftJoin('db_warehouse_config wc','p.config_id = wc.config_id')
            ->leftJoin('db_warehouse_out_son wos','wos.warehouse_out_son_id = p.warehouse_out_son_id')
            ->leftJoin('db_product pro','pro.goods_id = wos.goods_id')
            ->leftJoin('db_stock s','s.stock_id = p.stock_id')
            ->leftJoin('db_warehousing w','w.warehousing_id = s.warehousing_id')
            ->where('p.warehouse_out_id',$warehouse_out_id)->select()->toArray();

        $pick_no = !empty($pick) ? $pick[0]['pick_no'] : '';


        $warehouseOutSonTotalNumber = array_sum(array_column($warehouseOutSon,'number'));
        $warehouseOutSonTotalBoxNumber = array_sum(array_column($warehouseOutSon,'box_number'));
        $pickTotalNumber =  array_sum(array_column($pick,'number'));


        return [
            'warehouseOut'=>$warehouseOut,
            'warehouseOutSon'=>$warehouseOutSon,
            'pick'=>$pick,
            'pick_no'=>$pick_no,
            'warehouseOutSonTotalNumber'=>$warehouseOutSonTotalNumber,
            'warehouseOutSonTotalBoxNumber'=>$warehouseOutSonTotalBoxNumber,
            'pickTotalNumber'=>$pickTotalNumber
        ];
    }

    public function getEdiExportList()
    {
        $user = (new CatchAuth())->user();
        $user_id = $user->id;
        $tenant_id = $user['tenant_id'];
        $type = $user['type'];
        $where = [];

        if($tenant_id !== 0){
            $where[]=['w.tenant_id','=',$tenant_id];

            if($type==3){//员工账号，拿到所有项目
                $projectIds = (new Project)->where([
                    ['pid','>',0],
                    ['tenant_id','=',$tenant_id],
                    ['employees','find in set', $user_id],
                ])->column('project_id');
                $where[] = ['w.project_client','in',$projectIds];
            }
        }

        return $this->field('w.*')
        ->catchSearch()
            ->alias('w')
            ->leftJoin('db_project p','w.project_id = p.project_id')
            ->where($where)
            ->order($this->aliasField('id'), 'desc')
            ->select();
//            ->each(function (&$item){
//                $item['client_name'] = Db::table('db_project')
//                    ->where(['project_id' => $item['project_client']])
//                    ->value('project_name');
//                $item['project_name'] = Db::table('db_project')
//                    ->where(['project_id' => $item['project_id']])
//                    ->value('project_name');
//                $item['project_id'] = [$item['project_id'],$item['project_client']];
//                $item['ship_to_city'] = json_decode($item['ship_to_city'],true);
//                $item['shipper_city'] = json_decode($item['shipper_city'],true);
//                $item['pub_name'] = Db::table('users')
//                    ->where([['deleted_at','=',0],['id','=',$item['creator_id']]])
//                    ->value('username');
//            });

    }

    public function getExportList()
    {
        $user = (new CatchAuth())->user();
        $user_id = $user->id;
        $tenant_id = $user['tenant_id'];
        $type = $user['type'];
        $where = [];

        $where[] = ['w.support_export','=',1];

        if($tenant_id !== 0){
            $where[]=['w.tenant_id','=',$tenant_id];

            if($type==3){//员工账号，拿到所有项目
                $projectIds = (new Project)->where([
                    ['pid','>',0],
                    ['tenant_id','=',$tenant_id],
                    ['employees','find in set', $user_id],
                ])->column('project_id');
                $where[] = ['w.project_client','in',$projectIds];
            }
        }

        return $this->field('w.*')
            ->catchSearch()
            ->alias('w')
            ->leftJoin('db_project p','w.project_id = p.project_id')
            ->where($where)
            ->where('w.deleted_at',0)
            ->whereIn('w.status',['1','2'])
            ->order($this->aliasField('id'), 'desc')
            ->select();
//            ->each(function (&$item){
//                $item['client_name'] = Db::table('db_project')
//                    ->where(['project_id' => $item['project_client']])
//                    ->value('project_name');
//                $item['project_name'] = Db::table('db_project')
//                    ->where(['project_id' => $item['project_id']])
//                    ->value('project_name');
//                $item['project_id'] = [$item['project_id'],$item['project_client']];
//                $item['ship_to_city'] = json_decode($item['ship_to_city'],true);
//                $item['shipper_city'] = json_decode($item['shipper_city'],true);
//                $item['pub_name'] = Db::table('users')
//                    ->where([['deleted_at','=',0],['id','=',$item['creator_id']]])
//                    ->value('username');
//            });

    }
}
